package org.kth.dks.dks_marshal;

/**
 * <p>Title: DKS</p>
 * <p>Description: DKS Middleware</p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: KTH-IMIT</p>
 * @author Ali Ghodsi (aligh@kth.se)
 * @version 1.0
 */

import java.io.IOException;

import org.kth.dks.DKSObject;
import org.kth.dks.dks_node.LookupType;

public class LookupRequestMsg
    extends DKSMessage { // shouldnt be public!
  private static String NAME = "LOOKUPREQUEST";
  private long target;
  private LookupType type;
  private String msgId;
  private boolean internal;
  private DKSObject payload = null; // invariant: only used if type==LookupType.DATA

  public String getName() {
    return NAME;
  }

  public long getTarget() {
    return target;
  }

  public LookupType getType() {
    return type;
  }

  public String getMsgId() {
    return msgId;
  }

  public DKSObject getPayload() {
    return payload;
  }

  public boolean getInternal() {
    return internal;
  }

  public LookupRequestMsg() {

  }

  public LookupRequestMsg(long target, LookupType type, String msgId,
                          boolean intern) {

    this.target = target;
    this.type = type;
    this.msgId = msgId;
    this.internal = intern;
  }

  /* this version of the constructor has a DKSObject payload
      invariant: should only be used if type==LookupType.ASYNCDATA (or SYNCDATA), else above constructor should be used
   */
  public LookupRequestMsg(long target, LookupType type, DKSObject payload,
                          String msgId, boolean intern) {

    this.target = target;
    this.type = type;
    this.msgId = msgId;
    this.payload = payload;
    this.internal = intern;
  }

  public void marshal() throws IOException {
    marshaler.addLong(target, "target");
    marshaler.addString(type.toString(), "type");

    marshaler.addBool(payload == null ? false : true , "anypayload");
    if (payload != null) {
      marshaler.addDKSObject(payload, "payload");
    }

    marshaler.addBool(msgId == null ? false : true , "anyinsertid");
    if (msgId != null) {
      marshaler.addString(msgId, "insertid");
    }

    marshaler.addBool(internal, "internal");

  }

  public void unmarshal() throws IOException {

    target = marshaler.remLong("target");
    type = LookupType.valueOf(marshaler.remString("type"));

    final boolean anyLoad = marshaler.remBool("anypayload");
    if (anyLoad) {
      payload = marshaler.remDKSObject("payload");
    }

    final boolean anyId = marshaler.remBool("anyinsertid");
    if (anyId) {
      msgId = marshaler.remString("insertid");
    }

    internal = marshaler.remBool("internal");
  }

}
